{% extends "ceudp/base.html" %}
{% load staticfiles %}

{% block customize-style %}
    <style type="text/css">
        div.dataTables_filter {
            text-align: left;
        }
    </style>
{% endblock %}

{% block customize-script %}
<script>
    leaf_active("users"); // 激活左侧菜单栏图标效果
    $.ajaxSetup({
        data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
    });

    var user_table = null;
    var user_group_select = null;
    var user_permission_select = null;
    var modified_user_group_select = null;
    var modified_user_permission_select = null;
    var user_permissions = null;
    $.ajax({
        type: "GET",
        url: "{% url 'management_api:permission-list' %}",
        async: false,
        success: function(response){
            var data = [];
            for (var i = 0; i < response.length; i++) {
                data[i] = {
                    id: response[i].id,
                    text: response[i].name,
                };
            }

            user_permissions = data;
        },
        error: function(response){
            sweetAlert("错误", response.responseText, "error");
        },
    });

    var user_groups = null;
    $.ajax({
        type: "GET",
        url: "{% url 'management_api:group-list' %}",
        async: false,
        success: function(response){
            var data = [];
            for (var i = 0; i < response.length; i++) {
                data[i] = {
                    id: response[i].id,
                    text: response[i].name,
                };
            }

            user_groups = data;
        },
        error: function(response){
            sweetAlert("错误", response.responseText, "error");
        },
    });

    $(function(){
        user_table = $('#user_table').DataTable({
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "paginate": {
                    "first": "第一页",
                    "previous": "上一页",
                    "next": "下一页",
                    "last": "最后一页",
                },
            },
            "info": true,
            "paging": true,
            // "searching": false,
            "autoWidth": false,
            "processing": true,
            "bLengthChange": false, // 是否启动可以改变单页数量
            "iDisplayLength" : 20, // 设置单页显示数量
            "order": [[ 0, "asc" ]], // 默认 按第4列（从0开始）倒序排列
            "ajax": {
                "url": "{% url 'management_api:user-list' %}",
                "method": "GET",
                "timeout": 5000,
                "dataSrc": function(response){ return response },
                "error": function(response){
                    sweetAlert("错误", response.responseText, "error");
                },
            },
            "columns": [
                { 
                    "data": "id", "title": "编号",
                    "render": function(id){
                        var html = "<a href='#' data-toggle='modal' data-target='#user-modified-modal' onclick=show_user_modify(" + id + ")>" + 
                                id + 
                            "</a>";
                         return html;
                    },
                },
                { 
                    "data": "username", "title": "用户名",
                },
                { 
                    "data": "email", "title": "邮箱地址",
                },
                { 
                    "data": "created", "title": "创建时间",
                    "render": function(created){
                        var date = new Date(created);
                        return date.toLocaleDateString() + " " + date.toLocaleTimeString();
                    },
                },
                { 
                    "data": "modified", "title": "修改时间",
                    "render": function(modified){
                        var date = new Date(modified);
                        return date.toLocaleDateString() + " " + date.toLocaleTimeString();
                    },
                },
                { 
                    "data": "last_login", "title": "最后一次登录时间",
                    "render": function(last_login){
                        var date = new Date(last_login);
                        return date.toLocaleDateString() + " " + date.toLocaleTimeString();
                    },
                },
                { 
                    "data": "is_active", "title": "是否启用",
                    "render": function(is_active){
                        if (is_active) {
                            return "<span class='badge bg-green'><i class='fa fa-check'></i></span>";
                        } else {
                            return "<span class='badge bg-red'><i class='fa fa-close'></i></span>";
                        }
                    },
                },
            ],
            "dom": "<'#top-search.pull-left' f> <'#top-toolbar'>rtip",

        });

        // 顶部按钮
        var top_toolbar = "<div>" +
            "<div class='btn-group pull-right'>" +
                "<button type='button' class='btn btn-danger btn-sm' data-toggle='modal' data-target='#user-create-modal'>" + 
                    "<i class='fa fa-user-plus'></i>" +
                "</button>" +
            "</div>" +
        "</div>";
        $("#top-toolbar").html(top_toolbar);

        user_group_select = $(".user-groups").select2({
            data: user_groups,
            placeholder:"  请选择",//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true//允许清空
        });

        user_permission_select = $(".user-permissions").select2({
            data: user_permissions,
            placeholder:"  请选择",//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true//允许清空
        });
    });

    $("#create-btn").on("click", function(){
        var create_data = {
            "username": $("#create-username").val(),
            "verbose_name": $("#create-verbose-name").val(),
            "email": $("#create-email").val(), 
        }

        var user_group_vals = user_group_select.val();
        if (user_group_vals != null) {
            create_data["groups"] = user_group_vals;
        }

        var user_permission_vals = user_permission_select.val();
        if (user_permission_vals != null) {
            create_data["user_permissions"] = user_permission_vals;
        }

        $.ajax({
            type: "POST",
            url: "{% url 'management_api:user-list' %}",
            data: JSON.stringify(create_data),
            async: false,
            contentType: "application/json",
            success: function(response){
                sweetAlert("创建用户成功", "", "success");
                user_table.ajax.reload();
            },
            error: function(response){
                sweetAlert("错误", response.responseText, "error");
            },
        });

        $("#create-close-btn").click();
    });
    
    $("#modified-btn").on("click", function(){
        var modified_data = {
            "username": $("#modified-username").val(),
            "verbose_name": $("#modified-verbose-name").val(),
            "email": $("#modified-email").val(), 
        }

        var modified_user_group_vals = modified_user_group_select.val();
        if (modified_user_group_vals != null) {
            modified_data["groups"] = modified_user_group_vals;
        } else {
            modified_data["groups"] = [];
        }

        var modified_user_permission_vals = modified_user_permission_select.val();
        if (modified_user_permission_vals != null) {
            modified_data["user_permissions"] = modified_user_permission_vals;
        } else {
            modified_data["user_permissions"] = [];
        }

        $.ajax({
            type: "PATCH",
            url: "/api/management/users/" + $("#modified-id").val() + "/",
            data: JSON.stringify(modified_data),
            contentType: "application/json",
            async: false,
            success: function(response){
                sweetAlert("修改用户成功", "", "success");
                user_table.ajax.reload();
            },
            error: function(response){
                sweetAlert("错误", response.responseText, "error");
            },
        });

        $("#modified-close-btn").click();
    });

    function show_user_modify(id) {
        modified_user_group_select = $(".modified-user-groups").select2({
            data: user_groups,
            placeholder:"  请选择",//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true//允许清空
        });

        modified_user_permission_select = $(".modified-user-permissions").select2({
            data: user_permissions,
            placeholder:"  请选择",//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true//允许清空
        });

        $.ajax({
            type: "GET",
            url: "/api/management/users/" + id + "/",
            async: false,
            success: function(response){
                $("#modified-id").val(response.id);
                $("#modified-username").val(response.username);
                $("#modified-verbose-name").val(response.verbose_name);
                $("#modified-email").val(response.email);
                modified_user_group_select.val(response.groups).trigger("change");
                modified_user_permission_select.val(response.user_permissions).trigger("change");
            },
            error: function(response){
                $("#modified-close-btn").click();
                sweetAlert("错误", response.responseText, "error");
            },
        });
    }

</script>
{% endblock %}

{% block content %}
<div class="content-wrapper">
    <section class="content-header">
        <h1><i class="fa fa-user"></i> 用户管理<small>User Management</small></h1>
        <ol class="breadcrumb">
            <li><a href="{% url 'dashboard:index' %}"><i class="fa fa-dashboard"></i> 仪表盘 <small>[Dashboard]</small> </a></li>
            <li><a href="#"><i class="fa fa-sliders"></i>系统管理 <small>[Management]</small></a></li>
            <li class="active"><i class="fa fa-user"></i> 用户管理 <small>[Users]</small></li>
        </ol>
    </section>
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">用户列表</h3>
                    </div>
                    <div class="box-body">
                        <table id="user_table" class="table">
                            <thead>
                                <tr>
                                    <th>id</th>
                                    <th>username</th>
                                    <th>email</th>
                                    <th>created</th>
                                    <th>modified</th>
                                    <th>last_login</th>
                                    <th>is_active</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <div class="modal fade" id="user-create-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title"><i class="fa fa-user-plus"></i> 用户创建</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">用户名</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="create-username" placeholder="用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">显示名称</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="create-verbose-name" placeholder="显示中文名称">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-2 control-label">邮箱</label>
                            <div class="col-sm-9">
                                <input type="email" class="form-control" id="create-email" placeholder="邮箱">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="user-groups" class="col-sm-2 control-label">用户组</label>
                            <div class="col-sm-9">
                                <select class="user-groups" multiple="multiple" style="width: 90%;"></select>
                                <a href="{% url 'management:groups' %}" class="btn btn-primary btn-sm pull-right"><i class='fa fa-plus'></i></a>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="user-permissions" class="col-sm-2 control-label">权限</label>
                            <div class="col-sm-9">
                                <select class="user-permissions" multiple="multiple" style="width: 100%;"></select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger pull-left" data-dismiss="modal" id="create-close-btn">关闭</button>
                    <button type="button" class="btn btn-success" id="create-btn">创建</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="user-modified-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title"><i class="fa fa-user"></i> 修改用户</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">用户编号</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="modified-id" placeholder="用户编号" disabled>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">用户名</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="modified-username" placeholder="用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">显示名称</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="modified-verbose-name" placeholder="显示中文名称">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-2 control-label">邮箱</label>
                            <div class="col-sm-9">
                                <input type="email" class="form-control" id="modified-email" placeholder="邮箱">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="user-groups" class="col-sm-2 control-label">用户组</label>
                            <div class="col-sm-9">
                                <select class="modified-user-groups" multiple="multiple" style="width: 90%;"></select>
                                <a href="{% url 'management:groups' %}" class="btn btn-primary btn-sm pull-right"><i class='fa fa-plus'></i></a>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="user-permissions" class="col-sm-2 control-label">权限</label>
                            <div class="col-sm-9">
                                <select class="modified-user-permissions" multiple="multiple" style="width: 100%;"></select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger pull-left" data-dismiss="modal" id="modified-close-btn">关闭</button>
                    <button type="button" class="btn btn-success" id="modified-btn">修改</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}